package es.cazadoresmadridejos.beans.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import es.cazadoresmadridejos.beans.manager.access.AccessManager;
import es.cazadoresmadridejos.beans.manager.partner.PartnerManager;
import es.cazadoresmadridejos.model.Access;
import es.cazadoresmadridejos.model.Partner;
import es.cazadoresmadridejos.objs.security.User;

@Service(value="userDetailService")
public class UserDetailService implements UserDetailsService{

	@Autowired private PartnerManager partnerManager;
	@Autowired private AccessManager accessManager;
	@Autowired private PasswordEncoder passwordEncoder;
	
	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {
		
//		List<Partner> partners = partnerManager.findAll();
//		for (Partner partner : partners) {
//			
//			partner.setPassword(passwordEncoder.encodePassword(partner.getPassword(), User.getSalt()));
//			partnerManager.save(partner);
//		}
		
		Partner partner = partnerManager.getByName(arg0);
		if(partner == null){
			throw new UsernameNotFoundException("No existe el usuario " + arg0);
		}
		
		Access access = new Access();
		access.setDate(new Date());
		access.setLastName(partner.getLastName());
		access.setName(partner.getName());
		access.setUserId(partner.getId());
		
		accessManager.save(access);
		
		return new User(partner);
	}

}